<template>
    <view class="home-page">
        <!-- 用户信息卡片 -->
        <view class="user-card">
            <view class="user-info">
                <image
                    src="/static/images/avatar.png"
                    class="user-avatar"
                    mode="aspectFill"
                ></image>
                <view>
                    <text class="user-name">{{ userName }}</text>
                    <text class="user-status">孕{{ pregnancyWeeks }}周{{ pregnancyDays }}天</text>
                </view>
            </view>

            <view class="pregnancy-status">
                <view class="flex justify-between items-center mb-1">
                    <text class="text-sm font-medium text-gray-700">孕期进度</text>
                    <text class="text-xs text-pink-500">预产期：{{ dueDate }}</text>
                </view>

                <view class="progress-container">
                    <view class="progress-bar" :style="{ width: pregnancyProgress + '%' }"></view>
                </view>

                <view class="flex justify-between text-xs text-gray-500 mt-1">
                    <text>第一孕期</text>
                    <text>第二孕期</text>
                    <text>第三孕期</text>
                </view>
            </view>
        </view>

        <!-- 健康行为与饮食指导 -->
        <view class="health-guidance-section mb-3">
            <SectionTitle title="健康指导" icon="heart-beat" />

            <view class="guidance-cards">
                <view class="guidance-card" @click="pregnantNav.toPregnancyDiet">
                    <view class="guidance-icon bg-green">
                        <u-icon name="knife-fork" color="#FFFFFF" size="24"></u-icon>
                    </view>
                    <text class="guidance-title">孕期饮食指导</text>
                    <text class="guidance-desc">营养均衡保障</text>
                </view>

                <view class="guidance-card" @click="pregnantNav.toPregnancyExercise">
                    <view class="guidance-icon bg-blue">
                        <u-icon name="heart" color="#FFFFFF" size="24"></u-icon>
                    </view>
                    <text class="guidance-title">孕期运动建议</text>
                    <text class="guidance-desc">轻度活动促进血液循环</text>
                </view>
            </view>
        </view>

        <!-- 核心功能 -->
        <view class="core-functions mb-3">
            <SectionTitle title="孕期工具" icon="magic" />

            <FunctionGrid :columns="4">
                <FunctionItem
                    v-for="(item, index) in functionItems"
                    :key="index"
                    :icon="item.icon"
                    :name="item.name"
                    @click="item.action"
                />
            </FunctionGrid>
        </view>

        <!-- 胎儿发育数据 -->
        <ContentCard
            title="今日胎儿发育"
            icon="baby"
            more-text="详情"
            @more-click="pregnantNav.toFetalDevelopment"
        >
            <view class="space-y-3">
                <DataItem
                    icon="ruler"
                    label="胎儿身长"
                    :value="fetalLength"
                    unit="cm"
                    color="pink"
                />

                <DataItem
                    icon="weight"
                    label="胎儿体重"
                    :value="fetalWeight"
                    unit="g"
                    color="blue"
                />

                <DataItem
                    icon="apple-alt"
                    label="大小如同"
                    :value="fetalSizeComparison"
                    unit=""
                    color="green"
                />
            </view>

            <view class="fetal-development-info mt-3">
                <text class="text-sm">{{ fetalDevelopmentDescription }}</text>
            </view>
        </ContentCard>

        <!-- 孕期检查提醒 -->
        <ContentCard
            title="孕期检查提醒"
            icon="calendar-check"
            more-text="全部"
            @more-click="pregnantNav.toPregnancyCheckup"
        >
            <view class="checkup-list">
                <view class="checkup-item" v-for="(item, index) in checkupReminders" :key="index">
                    <view
                        class="checkup-icon"
                        :class="item.completed ? 'bg-green-100' : 'bg-pink-100'"
                    >
                        <u-icon
                            :name="item.completed ? 'checkmark-circle' : 'clock'"
                            :color="item.completed ? '#10B981' : '#FF9FB5'"
                            size="20"
                        ></u-icon>
                    </view>

                    <view class="checkup-content">
                        <view class="flex justify-between">
                            <text class="text-sm font-medium">{{ item.title }}</text>
                            <text class="text-xs text-gray-400">{{ item.date }}</text>
                        </view>
                        <text class="text-xs text-gray-500">{{ item.description }}</text>
                    </view>
                </view>
            </view>

            <button class="custom-button" @tap="pregnantNav.toPregnancyCheckup">
                <u-icon name="plus" color="#FF9FB5" size="14"></u-icon>
                <text>添加检查提醒</text>
            </button>
        </ContentCard>

        <!-- 孕期体重管理 -->
        <ContentCard
            title="孕期体重管理"
            icon="weight"
            more-text="趋势"
            @more-click="pregnantNav.toWeightTracker"
        >
            <view class="flex justify-between mb-3">
                <view class="flex flex-1 flex-col items-center">
                    <text class="text-xl font-bold text-pink-500">{{ currentWeight }}</text>
                    <text class="text-xs text-gray-500">当前体重(kg)</text>
                </view>

                <view class="flex flex-1 flex-col items-center">
                    <text class="text-xl font-bold text-blue-500">{{ weightGain }}</text>
                    <text class="text-xs text-gray-500">增重(kg)</text>
                </view>

                <view class="flex flex-1 flex-col items-center">
                    <text class="text-xl font-bold text-green-500">{{ targetWeightGain }}</text>
                    <text class="text-xs text-gray-500">目标增重(kg)</text>
                </view>
            </view>

            <view class="weight-chart">
                <text class="chart-placeholder">体重变化趋势图</text>
            </view>
        </ContentCard>

        <!-- 胎动计数 -->
        <ContentCard
            title="胎动记录"
            icon="heartbeat"
            more-text="历史"
            @more-click="pregnantNav.toKickCounter"
        >
            <view class="flex justify-between mb-3">
                <view class="text-sm">
                    今日已记录
                    <text class="font-semibold text-pink-500">{{ kickCount }}</text>
                    次胎动
                </view>
                <view class="text-sm text-gray-500">目标: 10次/小时</view>
            </view>

            <view class="kick-timeline">
                <view class="kick-time-point" v-for="(time, index) in kickTimes" :key="index">
                    <view class="kick-time-marker"></view>
                    <text class="kick-time-text">{{ time }}</text>
                </view>
            </view>

            <button class="custom-button" @tap="pregnantNav.toKickCounter">
                <u-icon name="plus" color="#FF9FB5" size="14"></u-icon>
                <text>记录胎动</text>
            </button>
        </ContentCard>

        <!-- 孕期知识推荐 -->
        <ContentCard
            title="孕期知识"
            icon="lightbulb"
            more-text="更多"
            @more-click="pregnantNav.toKnowledge"
        >
            <view class="article-list">
                <view
                    class="article-item"
                    v-for="(article, index) in articles"
                    :key="index"
                    @tap="viewArticleDetail(article.id)"
                >
                    <image :src="article.image" class="article-image" mode="aspectFill"></image>
                    <view class="article-content">
                        <text class="article-title">{{ article.title }}</text>
                        <view class="article-meta">
                            <view class="article-tag">{{ article.tag }}</view>
                            <view class="article-views">{{ article.views }}阅读</view>
                        </view>
                    </view>
                </view>
            </view>
        </ContentCard>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getUserData } from '@/services/userDataService'
import { calculatePregnancyWeeks, calculateDueDate } from '@/utils/dateUtils'
import { pregnantNavigation as pregnantNav } from '@/utils/navigationUtils'
import ContentCard from '@/components/home/ContentCard.vue'
import FunctionItem from '@/components/home/FunctionItem.vue'
import FunctionGrid from '@/components/home/FunctionGrid.vue'
import SectionTitle from '@/components/home/SectionTitle.vue'
import DataItem from '@/components/home/DataItem.vue'

// 获取用户数据
const userData = getUserData()

// 孕检提醒
const checkupReminders = ref([
    {
        title: '唐氏筛查',
        description: '孕16-20周，建议到三甲医院做',
        date: '07-20',
        completed: true
    },
    {
        title: '糖耐量检查',
        description: '孕24-28周，空腹前往医院',
        date: '08-15',
        completed: false
    }
])

// 胎动时间
const kickTimes = ref(['09:15', '10:30', '11:45', '13:20', '14:30', '16:10'])

// 文章列表
const articles = ref([
    {
        id: 1,
        title: '孕中期饮食指南：这些营养一定要补充',
        tag: '饮食指南',
        image: '/static/images/pregnant1.jpg',
        views: '1.8万'
    },
    {
        id: 2,
        title: '孕5个月胎儿发育详解及注意事项',
        tag: '胎儿发育',
        image: '/static/images/pregnant2.jpg',
        views: '1.2万'
    }
])

// 功能项列表
const functionItems = [
    { icon: 'baby', name: '胎儿发育', action: pregnantNav.toFetalDevelopment },
    { icon: 'utensils', name: '孕期饮食', action: pregnantNav.toPregnancyDiet },
    { icon: 'running', name: '孕期运动', action: pregnantNav.toPregnancyExercise },
    { icon: 'hospital', name: '产检计划', action: pregnantNav.toPregnancyCheckup },
    { icon: 'weight', name: '体重管理', action: pregnantNav.toWeightTracker },
    { icon: 'heartbeat', name: '胎动计数', action: pregnantNav.toKickCounter },
    { icon: 'suitcase', name: '待产包', action: pregnantNav.toHospitalBag },
    { icon: 'file-medical-alt', name: '生产计划', action: pregnantNav.toBirthPlan }
]

// 计算属性
const userName = computed(() => userData.userName || '张小梅')

// 计算孕周和天数
const { weeks: pregnancyWeeks, days: pregnancyDays } = computed(() => {
    return calculatePregnancyWeeks(userData.lastMenstrualPeriod || '')
}).value

// 计算预产期
const dueDate = computed(() => {
    const dueDateStr = calculateDueDate(userData.lastMenstrualPeriod || '')
    const date = new Date(dueDateStr)
    return `${date.getMonth() + 1}月${date.getDate()}日`
})

// 计算孕期进度（基于280天）
const pregnancyProgress = computed(() => {
    const totalDays = pregnancyWeeks * 7 + pregnancyDays
    return Math.min(Math.round((totalDays / 280) * 100), 100)
})

// 胎儿发育数据（根据孕周计算）
const fetalLength = computed(() => {
    // 根据孕周计算胎儿身长的示例值
    const lengthMap: Record<number, number> = {
        8: 1.6,
        12: 5.4,
        16: 12,
        20: 16,
        24: 30,
        28: 38,
        32: 42,
        36: 47,
        40: 51
    }

    // 找到最接近的周数
    const weeks = Object.keys(lengthMap)
        .map(Number)
        .sort((a, b) => {
            return Math.abs(a - pregnancyWeeks) - Math.abs(b - pregnancyWeeks)
        })[0]

    return lengthMap[weeks] || 0
})

const fetalWeight = computed(() => {
    // 根据孕周计算胎儿体重的示例值
    const weightMap: Record<number, number> = {
        8: 1,
        12: 14,
        16: 100,
        20: 300,
        24: 600,
        28: 1000,
        32: 1700,
        36: 2500,
        40: 3400
    }

    // 找到最接近的周数
    const weeks = Object.keys(weightMap)
        .map(Number)
        .sort((a, b) => {
            return Math.abs(a - pregnancyWeeks) - Math.abs(b - pregnancyWeeks)
        })[0]

    return weightMap[weeks] || 0
})

const fetalSizeComparison = computed(() => {
    // 根据孕周给出大小比喻
    const sizeMap: Record<number, string> = {
        8: '蓝莓',
        12: '青柠',
        16: '牛油果',
        20: '芒果',
        24: '玉米棒',
        28: '茄子',
        32: '椰子',
        36: '大白菜',
        40: '西瓜'
    }

    // 找到最接近的周数
    const weeks = Object.keys(sizeMap)
        .map(Number)
        .sort((a, b) => {
            return Math.abs(a - pregnancyWeeks) - Math.abs(b - pregnancyWeeks)
        })[0]

    return sizeMap[weeks] || ''
})

const fetalDevelopmentDescription = computed(() => {
    // 根据孕周给出发育描述
    if (pregnancyWeeks < 12) {
        return '胎儿正在快速发育中，开始形成主要器官和系统。此时需要特别注意补充叶酸。'
    } else if (pregnancyWeeks < 24) {
        return '胎儿各个器官继续发育，已经能感知外界声音，可以开始进行胎教。'
    } else {
        return '胎儿发育逐渐完善，皮下脂肪开始积累，准备好迎接世界。此时需注意控制体重增长速度。'
    }
})

const currentWeight = computed(() => '62.5') // 示例值
const weightGain = computed(() => '+5.8') // 示例值
const targetWeightGain = computed(() => '11.5') // 示例值，根据BMI计算
const kickCount = computed(() => kickTimes.value.length)

// 查看文章详情
const viewArticleDetail = (id: number) => {
    uni.navigateTo({ url: `/pages/knowledge/detail?id=${id}` })
}

// 生命周期钩子
onMounted(() => {
    // 初始化逻辑
})
</script>

<style lang="scss" scoped>
@import '@/styles/home.scss';

/* 用户信息卡片特定样式 */
.user-avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    margin-right: 20rpx;
    border: 4rpx solid #ffd6e0;
}

.user-info {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
}

.user-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    display: block;
}

.user-status {
    font-size: 24rpx;
    color: #666;
    display: block;
}

.pregnancy-status {
    background-color: #fff8f9;
    border-radius: 16rpx;
    padding: 20rpx;
}

/* 健康指导部分特定样式 */
.guidance-cards {
    display: flex;
    justify-content: space-between;
    gap: 20rpx;
}

.guidance-card {
    flex: 1;
    background-color: #ffffff;
    border-radius: 24rpx;
    padding: 40rpx 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
}

.guidance-icon {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20rpx;
}

.bg-green {
    background-color: #10b981;
}

.bg-blue {
    background-color: #60a5fa;
}

.guidance-title {
    font-size: 30rpx;
    color: #333333;
    font-weight: 500;
    margin-bottom: 10rpx;
    display: block;
}

.guidance-desc {
    font-size: 26rpx;
    color: #666666;
    display: block;
}

/* 胎儿发育信息样式 */
.fetal-development-info {
    background-color: #f9f9f9;
    border-radius: 16rpx;
    padding: 20rpx;
}

/* 孕检提醒样式 */
.checkup-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.checkup-item {
    display: flex;
    align-items: center;
}

.checkup-icon {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 20rpx;
}

.checkup-content {
    flex: 1;
}

/* 体重图表 */
.weight-chart {
    width: 100%;
    height: 200rpx;
    background-color: #f9f9f9;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20rpx;
}

.chart-placeholder {
    font-size: 24rpx;
    color: #999;
}

/* 胎动时间轴 */
.kick-timeline {
    display: flex;
    overflow-x: auto;
    padding: 20rpx 0;
}

.kick-time-point {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 40rpx;
}

.kick-time-marker {
    width: 16rpx;
    height: 16rpx;
    background-color: #ff9fb5;
    border-radius: 50%;
    margin-bottom: 10rpx;
}

.kick-time-text {
    font-size: 24rpx;
    color: #666;
}
</style>
